package cj.web.sc.controllers;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;

import cj.utils.Constants;
import cj.utils.ReturnUUID;
import cj.utils.sms.SendSMSUtil;
import cj.web.sc.dao.AppTokenDAO;
import cj.web.sc.util.AliyuncsSmsClient;
import cj.web.sc.util.ChuCaiSmsClient;
import cj.web.sc.util.TCaptchaVerify;

@Path("apptoken")
public class AppTokenController {

	@Autowired
	private AppTokenDAO appTokenDao; 
	
	private static final String CODE = "MESSAGE";
	
	private static final String CONFIG_CODE = "AUTH_CODE";
	
	/**
	 * 发送验证码----old
	 * @param phone	手机号
	 * @return
	 */
	@Get("sendToken")
	public String createLoginToken(@Param("phone") String phone) {
		
		List<Map> rep = appTokenDao.queryConfigInfo(CODE);
		JSONObject jo = new JSONObject();
		if(rep!=null && rep.size()>0){
			//短信（0融云，1阿里）
			String value = rep.get(0).get("value").toString();
			if(value.equals("0")){
				jo = sendTokenByYTX(phone);
			}else{
				jo = sendTokenByAliyuncs(phone);
			}
		}
		
		return "@"+jo.toString();
	}
	
	/**
	 * 云通讯短信平台
	 * @param phone
	 * @return
	 */
	private JSONObject sendTokenByYTX(String phone){
		String tempid="154081";//模版ID
		String params2="1分钟";//时间参数
		String accountSid="8aaf07085982d0f4015986faa6060210";
		String accountToken="2a2f32604b5a4622bbf9cfc26b9691bf";
		String appId="8aaf07085a1c6a8e015a21fa2d8801e9";
		
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		//验证码
		String token= ReturnUUID.getRandomNum();
		//组合为数组传递
		String[] msg = new String[]{token,params2};
		//调用短信平台
		String rep = SendSMSUtil.sendSMS(accountSid, accountToken, appId, phone, tempid, msg);
		if(rep.equals(Constants.returnObj.returnFlag_true)){
			appTokenDao.updateToken(phone);
			appTokenDao.createToken(phone, token);
		}else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return jo;
	}
	
	/**
	 * 云通讯短信平台
	 * @param phone
	 * @return
	 */
	private JSONObject sendTokenByAliyuncs(String phone){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		//验证码
		String token= ReturnUUID.getRandomNum();
		
		try {
			SendSmsResponse obj = AliyuncsSmsClient.sendSms(phone, token);
			if(obj.getCode().equals("OK")){
				appTokenDao.updateToken(phone);
				appTokenDao.createToken(phone, token);
			}else{
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			}
		} catch (ClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return jo;
	} 
	
	/**
	 * 楚才—企信通Web短信平台
	 * @param phone
	 * @return	http://v6.4006555441.com/login.aspx?err=
	 */
	private JSONObject sendTokenByRXT(String phone){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		//验证码
		String token= ReturnUUID.getRandomNum();
		
		String content = "您本次操作的效验码是"+token;
		ChuCaiSmsClient tt = new ChuCaiSmsClient();
		String res = tt.sendSms(phone, content);
		// 设置返回值
		/**
		 * 0:发送成功;-1:用户名或密码错误;-2:余额不足;-3:内容超过300字;
		 * -4:IP不符合;-7:手机号错误;-404:系统异常
		 */
		if(res.equals(Constants.returnObj.returnFlag_true)){
			appTokenDao.updateToken(phone);
			appTokenDao.createToken(phone, token);
		}
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return jo;
	}
	
	/**
	 * 发送验证码
	 * @param phone	手机号
	 * @return
	 */
	@Get("sendTokenTemp")
	public String createLoginTokenTemp(@Param("phone") String phone,@Param("key") String key,HttpSession session) {
		JSONObject jo = new JSONObject();

		//验证码判断
		boolean authCodeFlag = returnAuthCodeFlag(key, session);
				
		if(!authCodeFlag){
			//图形验证码失败
			jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
			return "@"+jo.toString();	
		}
		
		List<Map> rep = appTokenDao.queryConfigInfo(CODE);
		if(rep!=null && rep.size()>0){
			//短信（0融云，1阿里）
			String value = rep.get(0).get("value").toString();
			if(value.equals("0")){
				jo = sendTokenByYTX(phone);
			}else{
				jo = sendTokenByAliyuncs(phone);
			}
		}
		
		return "@"+jo.toString();	
	}
	
	/**
	 * 判断验证码是否开启，开启状态验证图形验证码
	 * @param key			验证码
	 * @param session
	 * @return
	 */
	private boolean returnAuthCodeFlag(String key, HttpSession session){
		boolean authCodeFlag = false;
		//获取配置的验证码值
		List<Map> authCodeObj = appTokenDao.queryConfigInfo(CONFIG_CODE);
		if(authCodeObj!=null && authCodeObj.size()>0){
			int authCodeValue = Integer.parseInt(authCodeObj.get(0).get("value").toString());
			//验证码（0开，1关）
			if(authCodeValue == 0){
				//验证图形验证码
				String strCode = session.getAttribute("strCode").toString();
				authCodeFlag = (strCode!=null && key.equals(strCode));
			}else{
				//验证码判断直接逻辑为真
				authCodeFlag = true;
			}
		}else{
			//验证图形验证码
			String strCode = session.getAttribute("strCode").toString();
			authCodeFlag = (strCode!=null && key.equals(strCode));
		}
		return authCodeFlag;
	}
	
	/**
	 * 发送验证码
	 * @param phone	手机号
	 * @return
	 */
	@Get("sendTokenTicket")
	public String sendTokenTicket(@Param("phone") String phone, @Param("key") String key,
			@Param("ticket") String ticket, @Param("randstr") String randstr, HttpSession session) {
		JSONObject jo = new JSONObject();
		
		int ticketCheckFlag = TCaptchaVerify.verifyTicket(ticket, randstr, "");
		
		if(ticketCheckFlag==-1 || ticketCheckFlag==100){
			jo.put("returnFlag", Constants.returnObj.returnFlag_3);
			return "@"+jo.toString();
		}
		
		//验证码判断
		boolean authCodeFlag = returnAuthCodeFlag(key, session);
				
		if(!authCodeFlag){
			//图形验证码失败
			jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
			return "@"+jo.toString();	
		}
		
		List<Map> rep = appTokenDao.queryConfigInfo(CODE);
		if(rep!=null && rep.size()>0){
			//短信（0融云，1阿里）
			String value = rep.get(0).get("value").toString();
			if(value.equals("0")){
				jo = sendTokenByYTX(phone);
			}else{
				jo = sendTokenByAliyuncs(phone);
			}
		}
		
		return "@"+jo.toString();	
	}
}